package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.View;

import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.T;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.api.ApiService;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AddAppBean;
import com.shenzhen.horselive.beans.AppBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.common.SafeConsumer;
import com.shenzhen.horselive.common.utils.Permissions;
import com.shenzhen.horselive.databinding.ActivityAddAppBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import gun0912.tedbottompicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AddAppActivity extends AppBarActivity {

    private static final int REQUEST_CODE_CHOOSE =9001 ;
    ActivityAddAppBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityAddAppBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("添加应用");
        initData();
        initViews();
    }

    AppBean  appBean;
    private void initData() {
        appBean = (AppBean) getIntent().getSerializableExtra("data");
        if (appBean!=null)
        {
            binding.etName.setText(appBean.getApplicationName());
            binding.etContent.setText(appBean.getApplicationDesc());
            binding.etUrl.setText(appBean.getApplicationUrl());
            GlideHelper.loadImage(appBean.getApplicationLogo(),binding.imgThree);

            binding.containerBts.setVisibility(View.VISIBLE);
            binding.btGo.setVisibility(View.GONE);
        }
        else
        {
            binding.containerBts.setVisibility(View.GONE);
            binding.btGo.setVisibility(View.VISIBLE);
        }
    }

    //应用名称
    private void initViews() {
        binding.etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                 binding.tvNum1.setText(s.length()+"/10");
            }
        });

        binding.etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.tvNum2.setText(s.length()+"/15");
            }
        });


        binding.imgThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });


        binding.btChage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                change();
            }
        });

        binding.btDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                del();
            }
        });


    }

    private void del() {
        ApiFactory.getApiService().delApp(User.get().getMyInfo().getToken(),appBean.getId()+"")
        .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("删除成功");
                            setResult(1001);
                            finish();
                        }else
                        {
                            showToast(commResponseBean.getErrMessage());
                        }

                    }
                });

    }

    private void submit() {
        String  name = binding.etName.getText().toString();
        if (TextUtils.isEmpty(name))
        {
            showToast("请输入应用名称");
            return;
        }

        String  content = binding.etContent.getText().toString();
        if (TextUtils.isEmpty(content))
        {
            showToast("请填写描述");
            return;
        }
        if (path==null)
        {
            showToast("请选择图片");
            return;
        }
        String  url = binding.etUrl.getText().toString();
        if (TextUtils.isEmpty(url))
        {
            showToast("请填写下载链接");
            return;
        }

        File  file = new File(path);
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("token", User.get().getMyInfo().getToken())
                .addFormDataPart("applicationName", name)
                .addFormDataPart("applicationDesc", content)
                .addFormDataPart("applicationUrl", url)
                .addFormDataPart("logoFile", file.getName(), fileBody)
                .setType(MultipartBody.FORM)
                .build()
                ;


        ApiFactory.getApiService().addApp(multipartBody)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AddAppBean>(this) {
                    @Override
                    protected void onNextInActive(AddAppBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("添加成功");
                            Intent  intent = new Intent();
                            intent.putExtra("data",commResponseBean.getData());
                            setResult(1001,intent);
                            finish();
                        }else
                        {
                            showToast(commResponseBean.getErrMessage());
                        }
                    }
                });


    }


    private void change() {
        String  name = binding.etName.getText().toString();
        if (TextUtils.isEmpty(name))
        {
            showToast("请输入应用名称");
            return;
        }

        String  content = binding.etContent.getText().toString();
        if (TextUtils.isEmpty(content))
        {
            showToast("请填写描述");

            return;
        }
        String  url = binding.etUrl.getText().toString();
        if (TextUtils.isEmpty(url))
        {
            showToast("请填写链接");
            return;
        }

        MultipartBody.Builder multipartBody = new MultipartBody.Builder()
                .addFormDataPart("token", User.get().getMyInfo().getToken())
                .addFormDataPart("id", appBean.getId()+"")
                .addFormDataPart("applicationName", name)
                .addFormDataPart("applicationDesc", content)
                .addFormDataPart("applicationUrl", url)
                .setType(MultipartBody.FORM)
                ;

        if (path!=null)
        {
            File  file = new File(path);
            RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
           multipartBody.addFormDataPart("logoFile", file.getName(), fileBody);
        }
        ApiFactory.getApiService().updateApp(multipartBody.build())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<AddAppBean>(this) {
                    @Override
                    protected void onNextInActive(AddAppBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("修改成功");
                            Intent  intent = new Intent();
                            intent.putExtra("data",commResponseBean.getData());
                            setResult(1001,intent);
                            finish();
                        }else
                        {
                            showToast(commResponseBean.getErrMessage());
                        }
                    }
                });


    }


    //选择照片
    String  path;
    private void chooseImage() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all)
                        {


                            Matisse.from(AddAppActivity.this)
                                    .choose(MimeType.ofImage())
                                    .countable(false)
                                    .maxSelectable(1)
                                    .showSingleMediaType(true)
//                                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
                                    .imageEngine(new GlideEngine())
//                                    .showPreview(false) // Default is `true`
                                    .forResult(REQUEST_CODE_CHOOSE);
                            //权限申请成功
//                            new PhotoPicker.Builder(AddAppActivity.this).setSelectMaxCount(1)
//                                    .setOnImageSelectedListener(new PhotoPicker.OnImageSelectedListener() {
//                                        @Override
//                                        public void onImageSelected(Pair<Uri, String> imagePath) {
//                                            path = imagePath.second;
//                                            GlideHelper.loadImage(imagePath.second,binding.imgThree);
//
//                                        }
//                                    }).create().show();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });


    }


      public static void start(Context context, AppBean  appBean) {
        Intent starter = new Intent(context, AddAppActivity.class);
        starter.putExtra("data",appBean);
        context.startActivity(starter);
    }


    List<String>  mSelected;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//            mSelected = Matisse.obtainResult(data);
            mSelected =   Matisse.obtainPathResult(data);
            if (mSelected!=null&&mSelected.size()>0)
            {
                path = mSelected.get(0);
               GlideHelper.loadImage(path,binding.imgThree);
            }
        }
    }
}